import { IPlank } from '@/types';
import { useEffect, useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import FetchData from './FetchData';
import { PlankSelect, JsonEditor } from '@/components';
import { IPlankListParams, bomApi } from '@/api';
import { isEmpty } from 'lodash-es';
import { message, Modal } from 'antd';
import * as fromOutApi from '@/api/from-out';

const log = console.log.bind(null, '[module:PlankOperater]');

interface Data {
  plankData: IPlank;
  holeId: string;
  grooveId: string;
  isUseCutting: boolean;
}

export function PlankOperator(props: {
  onChange: (data: Partial<Data>) => void;
}) {
  const [plankDatas, setPlankDatas] = useState<IPlank[]>([]);
  const [plankData, setPlankData] = useState<IPlank>();
  const [index, setIndex] = useState<number>(0);
  const [holeId, setHoleId] = useState<string>();
  const [grooveId, setGrooveId] = useState<string>();
  const [plankDataModalVisible, setPlankDataModalVisible] = useState(false);
  const [orderId, setOrderId] = useState<string>();
  const [mergeId, setMergeId] = useState<string>();
  const [tempJson, setTempJson] = useState<string>('');
  const plankDataJSON = JSON.stringify(plankData, null, 4);
  // 显示开料尺寸
  const [isUseCutting, setIsUseCutting] = useState(false);
  function onClickUseCutting() {
    setIsUseCutting(!isUseCutting);
  }

  useEffect(() => {
    props.onChange({ plankData, holeId, grooveId, isUseCutting });
  }, [plankData, holeId, grooveId, isUseCutting]);

  /** 适配外部参数注入 */
  const fromOutObj = {
    init() {
      fromOutApi.getParams().then(async (data) => {
        log('外部参数:', data);
        const { orderId, mergeId, plank } = data;
        if (plank) {
          setPlankData(plank);
          return;
        }
        if (orderId) {
          setOrderId(orderId);
          fetchPlankData({ orderId });
          return;
        }
        if (mergeId) {
          setMergeId(mergeId);
          fetchPlankData({ mergeId });
          return;
        }
      });
    },
  };
  useEffect(() => {
    fromOutObj.init();
  }, []);

  useEffect(() => {
    setTempJson(plankDataJSON);
  }, [plankDataJSON]);

  async function fetchPlankData(params: IPlankListParams) {
    return await bomApi.getPlankList(params).then((res) => {
      const planks = res.result;
      log('获取板件数据:', planks);
      if (isEmpty(planks)) {
        message.warn('板件数据为空，请检查订单信息');
      }
      setPlankDatas(planks);
      return planks;
    });
  }

  function resetCurrentPlank() {
    setIndex(0);
    setPlankData(plankDatas[0]);
  }

  useEffect(() => {
    resetCurrentPlank();
  }, [plankDatas]);

  useEffect(() => {
    if (isEmpty(plankDatas)) return;
    const plankData = plankDatas[index];
    // const shapeData = getShapeData(plankData)
    setPlankData(plankData);
    // setShapeData(shapeData)
  }, [plankDatas, index]);

  return (
    <>
      <span>
        <button onClick={onClickUseCutting}>
          {isUseCutting && '不'}显示开料尺寸
        </button>
        <FetchData
          onConfirm={(selected) => {
            // log({ selected });
            setPlankDatas(selected.data);
          }}
        />
        <label>订单ID</label>
        <input
          type="text"
          value={orderId}
          onChange={(e) => setOrderId(e.target.value)}
        />
        <button
          onClick={() => {
            fetchPlankData({ orderId });
          }}
        >
          搜索
        </button>
        <label>合批ID</label>
        <input
          type="text"
          value={mergeId}
          onChange={(e) => setMergeId(e.target.value)}
        />
        <button
          onClick={() => {
            fetchPlankData({ mergeId });
          }}
        >
          搜索
        </button>{' '}
      </span>
      <CopyToClipboard text={plankDataJSON} onCopy={() => alert('复制成功')}>
        <button>复制数据到剪贴板</button>
      </CopyToClipboard>
      <span>
        <button onClick={() => setPlankDataModalVisible(true)}>
          板件数据编辑
        </button>
        <Modal
          title="板件数据编辑"
          visible={plankDataModalVisible}
          footer={false}
          onCancel={() => {
            try {
              const data = JSON.parse(tempJson);
              setPlankData(data);
              setPlankDataModalVisible(false);
            } catch (error) {
              alert('JSON解析失败，请检测JSON格式是否正确');
            }
          }}
        >
          <JsonEditor
            htmlElementProps={{
              style: { width: '100%', height: 500 },
            }}
            allowedModes={['tree', 'code']}
            mode="code"
            value={tempJson}
            onChange={(obj) => {
              log('editor', { obj });
              const json = JSON.stringify(obj);
              // setPlankData(JSON.parse(json));
              setTempJson(json);
            }}
          />
        </Modal>
      </span>
      <span>
        <label>孔:</label>
        <select
          onChange={(e) => {
            // log(e.target.value)
            setHoleId(e.target.value);
          }}
        >
          <option value=""></option>
          {plankData?.holes.map((hole) => {
            return (
              <option key={hole.holeId} value={hole.holeId}>
                {hole.holeId}
              </option>
            );
          })}
        </select>
        <label>槽:</label>
        <select
          onChange={(e) => {
            // log(e.target.value)
            setGrooveId(e.target.value);
          }}
        >
          <option value=""></option>
          {plankData?.grooves.map((groove) => {
            return (
              <option key={groove.grooveId} value={groove.grooveId}>
                {groove.grooveId}
              </option>
            );
          })}
        </select>
      </span>
      <PlankSelect
        dataSource={plankDatas}
        onConfirm={(data) => {
          setIndex(plankDatas.indexOf(data));
          setPlankData(data);
        }}
      />
      <span>
        <button onClick={() => setIndex(index - 1)} disabled={index <= 0}>
          上一个
        </button>
        <button
          onClick={() => setIndex(index + 1)}
          disabled={index >= plankDatas.length - 1}
        >
          下一个
        </button>
        <span>
          {index + 1}/{plankDatas.length}
        </span>
      </span>
    </>
  );
}
